import React, { useState, useEffect } from "react";
import { Page, useNavigate, useLocation } from "zmp-ui";
import { useI18n } from "../i18n";
import Navbar from "../components/navbar";
import { handleZaloPayCallback } from "../api/endpoints";

const PaymentCallbackPage: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const location = useLocation();
  
  const [isProcessing, setIsProcessing] = useState(true);
  const [result, setResult] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    processPaymentCallback();
  }, []);

  const processPaymentCallback = async () => {
    try {
      // 从URL参数或state中获取回调数据
      const urlParams = new URLSearchParams(window.location.search);
      const callbackData = location.state?.callbackData || {
        data: urlParams.get('data') || '',
        mac: urlParams.get('mac') || ''
      };

      if (!callbackData.data || !callbackData.mac) {
        throw new Error('缺少回调数据');
      }

      // 调用后端处理支付回调
      const response = await handleZaloPayCallback(callbackData);
      
      if (response.code === 200) {
        setResult(response.data);
        // 支付成功，跳转到成功页面
        setTimeout(() => {
          navigate('/order-detail/success', {
            state: {
              orderInfo: response.data
            }
          });
        }, 2000);
      } else {
        setError(response.msg || t('payment.paymentFailed'));
      }
    } catch (err: any) {
      console.error('处理支付回调失败:', err);
      setError(err.message || t('payment.paymentFailed'));
    } finally {
      setIsProcessing(false);
    }
  };

  const handleRetry = () => {
    setIsProcessing(true);
    setError(null);
    processPaymentCallback();
  };

  const handleBack = () => {
    navigate('/create-order');
  };

  return (
    <Page className="page" style={{ backgroundColor: '#F5F5F7', padding: 0 }}>
      <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
        <Navbar title={t('payment.callbackTitle')} />
      </div>

      <div style={{ 
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '40px 20px'
      }}>
        {isProcessing ? (
          <>
            {/* 处理中图标 */}
            <div style={{
              width: '80px',
              height: '80px',
              backgroundColor: '#FF6B35',
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: '24px',
              animation: 'spin 1s linear infinite'
            }}>
              <span style={{ 
                color: '#fff', 
                fontSize: '24px'
              }}>
                ⏳
              </span>
            </div>

            {/* 处理中文本 */}
            <div style={{
              fontSize: '18px',
              fontWeight: 'bold',
              color: '#333',
              textAlign: 'center',
              marginBottom: '12px'
            }}>
              {t('payment.processingCallback')}
            </div>

            <div style={{
              fontSize: '14px',
              color: '#666',
              textAlign: 'center',
              lineHeight: '1.5'
            }}>
              {t('payment.callbackDesc')}
            </div>
          </>
        ) : error ? (
          <>
            {/* 错误图标 */}
            <div style={{
              width: '80px',
              height: '80px',
              backgroundColor: '#F44336',
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: '24px'
            }}>
              <span style={{ 
                color: '#fff', 
                fontSize: '40px',
                fontWeight: 'bold'
              }}>
                ✗
              </span>
            </div>

            {/* 错误文本 */}
            <div style={{
              fontSize: '18px',
              fontWeight: 'bold',
              color: '#333',
              textAlign: 'center',
              marginBottom: '12px'
            }}>
              {t('payment.callbackFailed')}
            </div>

            <div style={{
              fontSize: '14px',
              color: '#666',
              textAlign: 'center',
              marginBottom: '32px',
              lineHeight: '1.5'
            }}>
              {error}
            </div>

            {/* 操作按钮 */}
            <div style={{ width: '100%' }}>
              <button
                onClick={handleRetry}
                style={{
                  width: '100%',
                  height: '48px',
                  backgroundColor: '#FF6B35',
                  color: '#fff',
                  border: 'none',
                  borderRadius: '24px',
                  fontSize: '16px',
                  fontWeight: 'bold',
                  cursor: 'pointer',
                  marginBottom: '12px',
                  transition: 'all 0.2s'
                }}
              >
                {t('payment.retry')}
              </button>
              
              <button
                onClick={handleBack}
                style={{
                  width: '100%',
                  height: '48px',
                  backgroundColor: 'transparent',
                  color: '#666',
                  border: '2px solid #E5E5E5',
                  borderRadius: '24px',
                  fontSize: '16px',
                  fontWeight: 'bold',
                  cursor: 'pointer',
                  transition: 'all 0.2s'
                }}
              >
                {t('payment.backToPayment')}
              </button>
            </div>
          </>
        ) : (
          <>
            {/* 成功图标 */}
            <div style={{
              width: '80px',
              height: '80px',
              backgroundColor: '#4CAF50',
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: '24px'
            }}>
              <span style={{ 
                color: '#fff', 
                fontSize: '40px',
                fontWeight: 'bold'
              }}>
                ✓
              </span>
            </div>

            {/* 成功文本 */}
            <div style={{
              fontSize: '18px',
              fontWeight: 'bold',
              color: '#333',
              textAlign: 'center',
              marginBottom: '12px'
            }}>
              {t('payment.callbackSuccess')}
            </div>

            <div style={{
              fontSize: '14px',
              color: '#666',
              textAlign: 'center',
              lineHeight: '1.5'
            }}>
              {t('payment.redirecting')}
            </div>
          </>
        )}
      </div>

      <style>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </Page>
  );
};

export default PaymentCallbackPage;
